package com.luckmgr.util;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import com.common.utils.WDWUtil;

public class ExcelUtil {

	public static Map<String, List<String[]>> findExcelMap(MultipartFile file)
			throws Exception {
		Map<String, List<String[]>> map = new HashMap<String, List<String[]>>();
		InputStream in = file.getInputStream();// 获取控件内容的输入流
		Workbook workbook = null; 
		if (WDWUtil.isExcel2003(file.getOriginalFilename()))  
        {  
            workbook = new HSSFWorkbook(in);  
        }  
        else  
        {  
            workbook = new XSSFWorkbook(in);  
        }  
		
		int booknumber = workbook.getNumberOfSheets();

		for (int i = 0; i < booknumber; i++) {
			Sheet sheet = workbook.getSheetAt(i);
			List<String[]> list = new ArrayList<String[]>();
			map.put(sheet.getSheetName(), list);
			int regionsn = sheet.getLastRowNum();
			for (int j = 0; j <= regionsn; j++) {
				Row rowTitle = sheet.getRow(j);
				if(null != rowTitle){
					int rownum = rowTitle.getLastCellNum();
					if(rownum>0){
						String[] rows = new String[rownum];
						for (int k = 0; k < rownum; k++) {
							rows[k] = getCell(rowTitle.getCell(k));
						}
						list.add(rows);
					}
				}
				
			}
		}
		return map;
	}

	public static String getCell(Cell cell) {
		if (cell == null)
			return "";
		cell.setCellType(Cell.CELL_TYPE_STRING);
		switch (cell.getCellType()) {
		case HSSFCell.CELL_TYPE_NUMERIC:
			if (HSSFDateUtil.isCellDateFormatted(cell)) {
                Date date = cell.getDateCellValue();
                if (date != null) {
                	return new SimpleDateFormat("yyyy-MM-dd")
                      .format(date);
                } else {
                	return "";
                }
              } else {
                //如果格式为数值，自定义格式输出
            	  return cell.getStringCellValue();
              }
		case HSSFCell.CELL_TYPE_STRING:
			return cell.getStringCellValue();
		case HSSFCell.CELL_TYPE_FORMULA:
			return cell.getCellFormula();
		case HSSFCell.CELL_TYPE_BLANK:
			return "";
		case HSSFCell.CELL_TYPE_BOOLEAN:
			return cell.getBooleanCellValue() + "";
		case HSSFCell.CELL_TYPE_ERROR:
			return cell.getErrorCellValue() + "";
		}
		return "";
	}
}
